from flask import Blueprint, request, jsonify
from baiduAPI import face_register, face_search
from db import get_db
import json

face = Blueprint('face', __name__)

@face.route('/', methods=['POST'])
def addface():
    userinfo = request.json['userinfo']
    uid = userinfo['uid']
    img = request.json['img']
    
    import base64
    
    # 去掉base64编码的头部
    img_data = img.split(',')[1]
    img_binary = base64.b64decode(img_data)
    
    import numpy as np
    import cv2
    nparr = np.frombuffer(img_binary, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    
    # opencv 人脸检测器
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
    # 检测人脸
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    img_orig = img.copy()
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
        
    # for debug
    cv2.imwrite('/Users/calculus/other/MeetingAndFace/backend/face/face_detected.png', img)
    if len(faces) > 0:
        x, y, w, h = faces[0]
        face_img = img_orig[y:y+h, x:x+w]
        cv2.imwrite('/Users/calculus/other/MeetingAndFace/backend/face/face_cropped.png', face_img)
        
        _, buffer = cv2.imencode('.png', face_img)
        face_base64 = base64.b64encode(buffer).decode('utf-8')

        baiduapi_result = face_register(face_base64, uid, userinfo)
        
        if baiduapi_result['error_code'] == 0:
            db = get_db()
            try:
                with db.cursor() as cursor:
                    sql = f"UPDATE USER SET have_face = 1 WHERE uid = {uid}"
                    cursor.execute(sql)
                    db.commit()
            except Exception as e:
                db.rollback()
                return jsonify({
                    "result": False,
                    "info": f"人脸注册成功但数据库更新失败: {str(e)}"
                })
            finally:
                db.close()
            
            return jsonify({
                "result": True,
                "info": json.dumps(baiduapi_result)
            })
        else:
            return jsonify({
                "result": False,
                "info": json.dumps(baiduapi_result)
            })
            
    else:
        return jsonify({
            "result": False,
            "info": "未检测到人脸"
        })

@face.route('/search', methods=['POST'])
def search_face():
    img = request.json['img']
    result = face_search(img)
    return jsonify(result)

    
